package controller;

import common.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.NewsHeadline;
import service.NewsHeadlineService;
import service.impl.NewsHeadlineServiceImpl;
import util.JwtHelper;
import util.WebUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
// 处理新闻头条相关请求控制器类，继承基础控制器（获得请求分发能力
@WebServlet("/headline/*")
public class NewsHeadlineController extends BaseController {
    //业务对象初始化 基于接口编程 降低控制器与业务实现的耦合
    private NewsHeadlineService headlineService =new NewsHeadlineServiceImpl();
    /**
     * 删除头条业务接口 实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void removeByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        int hid = Integer.parseInt(req.getParameter("hid"));//获取客户端提交的请求参数，GET在URL中拼接的键值对POST表单默认提交也是键值对
        headlineService.removeByHid(hid);
        WebUtil.writeJson(resp,Result.ok(null));

    }
    /**
     * 更新头条的业务接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        //反序列化转为对应JAVA对象
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        headlineService.update(newsHeadline);
        //返回成功响应
        WebUtil.writeJson(resp,Result.ok(null));
    }
    /**
     * 修改头条回显业务接口
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findHeadlineByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 获取请求栈参数转为整数
        Integer hid = Integer.parseInt(req.getParameter("hid"));
        NewsHeadline headline =headlineService.findByHid(hid);
        //将查询结果封装MAP便于JSON序列化
        Map data =new HashMap();
        data.put("headline",headline);//前端接收后解析该对象中数据
        WebUtil.writeJson(resp,Result.ok(data));
    }
    /**
     * 发布头条的接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void publish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收参数
        String token = req.getHeader("token");
        Long userId = JwtHelper.getUserId(token);
        // 将请求体中的JSON转为对象
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        newsHeadline.setPublisher(userId.intValue());
        // 将信息存入数据库
        headlineService.addNewsHeadline(newsHeadline);
        WebUtil.writeJson(resp, Result.ok(null));
    }
}
